package codeRandomThoughts.Test583两个字符串的删除操作;

public class Solution {
    public int minDistance(String word1, String word2) {
        //其实就是求出word1和word2的最长公共子序列
        //最小步数就是word1和word2变成最长公共子序列需要删除多少个字符
        int maxLen = longestCommonSubsequence(word1, word2);
        return word1.length() + word2.length() - 2 * maxLen;
    }

    //求最长公共子序列
    public int longestCommonSubsequence(String word1, String word2) {
        char[] char1 = word1.toCharArray();
        char[] char2 = word2.toCharArray();

        int[][] dp = new int[char1.length + 1][char2.length + 1];
        int maxLen = 0;

        for (int i = 1; i <= char1.length; i++) {
            for (int j = 1; j <= char2.length; j++) {
                if (char1[i - 1] == char2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
                if (dp[i][j] > maxLen) {
                    maxLen = dp[i][j];
                }
            }
        }

        return maxLen;
    }
}
